﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using loginSQL.PrinterHelper;
using System.Runtime.InteropServices;
using System.IO;
using loginSQL.SQLHelper;
using loginSQL.Pages;
using loginSQL.Template;
using System.Text.RegularExpressions;
using loginSQL.Window;
using loginSQL.Util;

namespace loginSQL.DataView
{
    public partial class Preview : Form
    {
        int currentIdx;
        string userId;
        List<Image> imageList = new List<Image>();
        List<string> dataUser = new List<string>();
        List<AbstractPage> pages = new List<AbstractPage>();
        Point lastMousePosition = new Point();

        private delegate void updateDelegate();

        public Preview()
        {
            InitializeComponent();
            initListImage();
            InitImageCanvas();
            initListImage();
            updateDataSource();
        }

        public Preview(string userId,string licenseName, int activeLicenseID)
        {
            InitializeComponent();
            this.userId = userId;
            this.licenseName = licenseName;
            this.licenseID = activeLicenseID;
            this.currentIdx = 0;
            dragenabled = true;
            collections = Constants.collections;
            book = collections.GetBook(licenseName);
            DBHelper dbHelper = new DBHelper();
            dataUser = dbHelper.getDataUserFromIdNumber(this.userId,0);
            initListImage();
            InitImageCanvas();
            initListPage();
            margin_left.Text = Constants.PixelXToMilimeter(pages[currentIdx].getTopLeftX())+"";
            margin_top.Text = Constants.PixelYToMilimeter(pages[currentIdx].getTopLeftY()) + "";
            updateDataSource();
        }

        private void initListImage()
        {
            imageList.Add(new Bitmap(Properties.Resources.hal1));
            imageList.Add(new Bitmap(Properties.Resources._2));
            imageList.Add(new Bitmap(Properties.Resources._3));
            imageList.Add(new Bitmap(Properties.Resources._4));
            imageList.Add(new Bitmap(Properties.Resources._5));
            imageList.Add(new Bitmap(Properties.Resources._6));
            imageList.Add(new Bitmap(Properties.Resources._7));
            imageList.Add(new Bitmap(Properties.Resources._8));
            imageList.Add(new Bitmap(Properties.Resources._9));
        }

        private void initListPage()
        {
            /*
            PointF[] pointArray = new PointF[]{
                new PointF(105,32),
                new PointF(123,49),
                new PointF(123,57),
                new PointF(123,67),
                new PointF(123,77),
                new PointF(123,88)
            };

            List<PointF> secondPageArray = new List<PointF>(new PointF[]{new PointF(0,0)});
            //Pages Initiation
            Page firstpage = new Page(dataUser.GetRange(1,6), new List<PointF>(pointArray));
            pages.Add(firstpage);
            Page secondPage = new Page(dataUser.GetRange(7, 1),secondPageArray );
            pages.Add(secondPage);
             */
            //testing
            user = new Users(this.userId,licenseID);
            
            /*
            int pagesCount = Templates.PagesDefaultMargin.Count;
            foreach (List<PointF> pointfs in Templates.PagesDefaultMargin)
            {
                List<PointF> newpoint = new List<PointF>(pointfs);
                Page page = new Page(dataUser.GetRange(1, 6), newpoint);
                pages.Add(page);
            }
             */
            pages.Clear();
            int pagesCount = book.PageCount;
            foreach (PageData pageData in book.PageData)
            {
                List<String> dataList = new List<String>();
                List<PointF> pointArray = new List<PointF>();
                foreach (String key in pageData.AttributeName)
                {
                    if (pageData.IsVisible(key))
                    {
                        PointF point = pageData.GetData(key);
                        if (Users.IsPerpanjangan(key))
                        {
                            int curPerpanjangan = user.licenses[licenseID].current_perpanjangan_print_index;
                            float stepPixelY = (7 /*mili*/ * curPerpanjangan);
                            point.Y += stepPixelY;
                        }
                        else if(Users.IsKlasifikasiRating(key))
                        {
                            int curPerpanjangan = user.licenses[licenseID].current_klasifikasi_rating_print_index;
                            float stepPixelY = (8 /*mili*/ * curPerpanjangan);
                            point.Y += stepPixelY;
                        }
                        else if (Users.IsPerpanjanganRating(key))
                        {
                            int curPerpanjangan = user.licenses[licenseID].current_perpanjangan_rating_print_index;
                            float stepPixelY = (21 /*mili*/ * curPerpanjangan);
                            point.Y += stepPixelY;
                        }
                        else if (Users.IsCatatan(key))
                        {
                            int curPerpanjangan = user.licenses[licenseID].current_catatan_print_index;
                            float stepPixelY = (9.5f /*mili*/ * curPerpanjangan);
                            point.Y += stepPixelY;
                        }
                        dataList.Add(user.getDataFromKey(key));
                        pointArray.Add(point);
                    }
                }
                Page page = new Page(dataList, pointArray);
                pages.Add(page);
            }
            //last mouse initiation
            lastMousePosition = new Point((int)pages[0].getTopLeftX(), (int)pages[0].getTopLeftY());
            //draw firstpage
            pages[0].Draw(Graphics.FromImage(pic_preview.Image));
        }

        private void InitImageCanvas()
        {
            if (imageList.Count > 0)
            {
                currentIdx = 0;
                pic_preview.Image = new Bitmap(imageList[currentIdx]);
            }
        }
        
        public Image InsertDatatoBitmap(Image bitmap)
        {
            return null;
        }
        
        #region Printing Helper

        private const string PrinterName = @"EPSON PLQ-20 ESC/P2";
        private bool isDrag=false;
        private string licenseName;
        private BookCollection collections;
        private BookData book;
        private bool dragenabled;
        private int licenseID;
        private Users user;
        
        private class BitmapData
        {
            public BitArray Dots
            {
                get;
                set;
            }

            public int Height
            {
                get;
                set;
            }

            public int Width
            {
                get;
                set;
            }
        }

        private  BitmapData GetBitmapData(Image bitmaps)
        {
            using (var bitmap = (Bitmap)bitmaps)
            {
                var threshold = 127;
                var index = 0;
                var dimensions = bitmap.Width * bitmap.Height;
                var dots = new BitArray(dimensions);

                for (var y = 0; y < bitmap.Height; y++)
                {
                    for (var x = 0; x < bitmap.Width; x++)
                    {
                        var color = bitmap.GetPixel(x, y);
                        var luminance = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
                        dots[index] = (luminance < threshold);
                        index++;
                    }
                }

                return new BitmapData()
                {
                    Dots = dots,
                    Height = bitmap.Height,
                    Width = bitmap.Width
                };
            }
        }

        private byte[] GetDocument()
        {
            using (var ms = new MemoryStream())
            using (var bw = new BinaryWriter(ms))
            {
                // Reset the printer bws (NV images are not cleared)
                bw.Write(AsciiControlChars.Escape);
                bw.Write('@');

                // Render the logo
                //Bitmap imgTemp = new Bitmap(imageList[currentIdx]);
                Bitmap imgTemp = new Bitmap(pages[currentIdx].getPrintReadyImage());
                RenderLogo(bw,imgTemp);

                // Feed 3 vertical motion units and cut the paper with a 1 point cut
                //bw.Write(AsciiControlChars.GroupSeparator);
                //bw.Write('V');
                //bw.Write((byte)66);
                bw.Write((byte)3);

                bw.Flush();

                return ms.ToArray();
            }
        }

        private void RenderLogo(BinaryWriter bw,Image bitmaps)
        {
            var data = GetBitmapData(bitmaps);
            var dots = data.Dots;
            var width = BitConverter.GetBytes(data.Width);

            //bw.Write(AsciiControlChars.Newline);
            //bw.Write("CASE 1");
            //bw.Write(AsciiControlChars.Newline);

            //bw.Write(AsciiControlChars.Escape);
            //bw.Write('*');         // bit-image mode
            //bw.Write((byte)0);     // 8-dot single-density
            //bw.Write((byte)5);     // width low byte
            //bw.Write((byte)0);     // width high byte
            //bw.Write((byte)128);
            //bw.Write((byte)64);
            //bw.Write((byte)32);
            //bw.Write((byte)16);
            //bw.Write((byte)8);

            //bw.Write(AsciiControlChars.Newline);
            //bw.Write("CASE 2");
            //bw.Write(AsciiControlChars.Newline);

            //bw.Write(AsciiControlChars.Escape);
            //bw.Write('*');         // bit-image mode
            //bw.Write((byte)0);     // 8-dot single-density
            //bw.Write((byte)5);     // width low byte
            //bw.Write((byte)0);     // width high byte
            //bw.Write((byte)1);
            //bw.Write((byte)2);
            //bw.Write((byte)4);
            //bw.Write((byte)8);
            //bw.Write((byte)16);

            //bw.Write(AsciiControlChars.Newline);


            //bw.Write(AsciiControlChars.Newline);
            //bw.Write("CASE 3");
            //bw.Write(AsciiControlChars.Newline);

            // So we have our bitmap data sitting in a bit array called "dots."
            // This is one long array of 1s (black) and 0s (white) pixels arranged
            // as if we had scanned the bitmap from top to bottom, left to right.
            // The printer wants to see these arranged in bytes stacked three high.
            // So, essentially, we need to read 24 bits for x = 0, generate those
            // bytes, and send them to the printer, then keep increasing x. If our
            // image is more than 24 dots high, we have to send a second bit image
            // command.

            // Set the line spacing to 24 dots, the height of each "stripe" of the
            // image that we're drawing.
            bw.Write(AsciiControlChars.Escape);
            bw.Write('3');
            bw.Write((byte)24);

            // OK. So, starting from x = 0, read 24 bits down and send that data
            // to the printer.
            int offset = 0;

            while (offset < data.Height)
            {
                bw.Write(AsciiControlChars.Escape);
                bw.Write('*');         // bit-image mode
                bw.Write((byte)33);    // 24-dot double-density
                bw.Write(width[0]);  // width low byte
                bw.Write(width[1]);  // width high byte

                for (int x = 0; x < data.Width; ++x)
                {
                    for (int k = 0; k < 3; ++k)
                    {
                        byte slice = 0;

                        for (int b = 0; b < 8; ++b)
                        {
                            int y = (((offset / 8) + k) * 8) + b;

                            // Calculate the location of the pixel we want in the bit array.
                            // It'll be at (y * width) + x.
                            int i = (y * data.Width) + x;

                            // If the image is shorter than 24 dots, pad with zero.
                            bool v = false;
                            if (i < dots.Length)
                            {
                                v = dots[i];
                            }

                            slice |= (byte)((v ? 1 : 0) << (7 - b));
                        }

                        bw.Write(slice);
                    }
                }

                offset += 24;
                bw.Write(AsciiControlChars.Newline);
            }

            // Restore the line spacing to the default of 30 dots.
            //bw.Write(AsciiControlChars.Escape);
            //bw.Write('3');
            //bw.Write((byte)30);
        }

        private void Print(string printerName, byte[] document)
        {
            NativeMethods.DOC_INFO_1 documentInfo;
            IntPtr printerHandle;

            documentInfo = new NativeMethods.DOC_INFO_1();
            documentInfo.pDataType = "RAW";
            documentInfo.pDocName = "Bit Image Test";

            printerHandle = new IntPtr(0);

            if (NativeMethods.OpenPrinter(printerName.Normalize(), out printerHandle, IntPtr.Zero))
            {
                if (NativeMethods.StartDocPrinter(printerHandle, 1, documentInfo))
                {
                    int bytesWritten;
                    byte[] managedData;
                    IntPtr unmanagedData;

                    managedData = document;
                    unmanagedData = Marshal.AllocCoTaskMem(managedData.Length);
                    Marshal.Copy(managedData, 0, unmanagedData, managedData.Length);

                    if (NativeMethods.StartPagePrinter(printerHandle))
                    {
                        NativeMethods.WritePrinter(
                            printerHandle,
                            unmanagedData,
                            managedData.Length,
                            out bytesWritten);
                        NativeMethods.EndPagePrinter(printerHandle);
                    }
                    else
                    {
                        throw new Win32Exception();
                    }

                    Marshal.FreeCoTaskMem(unmanagedData);

                    NativeMethods.EndDocPrinter(printerHandle);
                }
                else
                {
                    throw new Win32Exception();
                }

                NativeMethods.ClosePrinter(printerHandle);
            }
            else
            {
                throw new Win32Exception();
            }
        }
        #endregion

        private void btn_print_Click(object sender, EventArgs e)
        {
            Print(PrinterName, GetDocument());
            DBHelper db = new DBHelper();
            List<int> incrementFound=new List<int>();
            List<int> valueFound=new List<int>();
            PageData curpage=book.PageData[currentIdx];
            foreach(String name in curpage.AttributeName)
            {
                if(curpage.IsVisible(name))
                {
                    if(Users.IsPerpanjangan(name))
                    {
                        incrementFound.Add(DBHelper.Perpanjangan_Index);
                        valueFound.Add(++user.licenses[licenseID].current_perpanjangan_print_index);
                    }
                    else if(Users.IsKlasifikasiRating(name))
                    {
                        incrementFound.Add(DBHelper.Klasifikasi_Index);
                        valueFound.Add(++user.licenses[licenseID].current_klasifikasi_rating_print_index);
                    }
                    else if(Users.IsPerpanjanganRating(name))
                    {
                        incrementFound.Add(DBHelper.Rating_Perpanjangan_Index);
                        valueFound.Add(++user.licenses[licenseID].current_perpanjangan_rating_print_index);
                    }
                    else if(Users.IsCatatan(name))
                    {
                        incrementFound.Add(DBHelper.Catatan_Index);
                        valueFound.Add(++user.licenses[licenseID].current_catatan_print_index);
                    }
                }
            }
            for(int i=0;i<incrementFound.Count;i++)
            {
                db.updatePrintIndexCount(userId,user.licenses[licenseID].license_id,user.licenses[licenseID].license_level_id,valueFound[i],incrementFound[i]);
            }
        }

        private void btn_next_Click(object sender, EventArgs e)
        {
            currentIdx++;
            btn_prev.Enabled = true;
            if (currentIdx == book.PageCount)
            {
                currentIdx = book.PageCount - 1;
                btn_next.Enabled = false;
            }
            update();
            updateDataSource();
            
        }

        private void btn_prev_Click(object sender, EventArgs e)
        {
            currentIdx--;
            btn_next.Enabled = true;
            if (currentIdx < 0)
            {
                currentIdx = 0;
                btn_prev.Enabled = false;
            }
            update();
            updateDataSource();            
        }

        private void updateImage()
        {
            pic_preview.Image = new Bitmap(imageList[currentIdx]);
            if (currentIdx < pages.Count)
            {
                Graphics g = Graphics.FromImage(pic_preview.Image);
                pages[currentIdx].Draw(g);
            }
        }

        private void updater_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void pic_preview_MouseHover(object sender, EventArgs e)
        {
           
        }

        private void pic_preview_MouseLeave(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.Default;
        }

        private void btn_set_Click(object sender, EventArgs e)
        {
            if (margin_left.Text != "" && margin_top.Text != "")
            {
                try
                {
                    float marginLeft = Constants.MilimeterXToPixel((float)Convert.ToDouble(margin_left.Text));
                    float marginTop = Constants.MilimeterYToPixel((float)Convert.ToDouble(margin_top.Text));
                    float diffLeft = marginLeft - this.pages[currentIdx].getTopLeftX();
                    float diffTop = marginTop- this.pages[currentIdx].getTopLeftY();
                    ((Page)(this.pages[currentIdx])).movePixelXY((int)diffLeft, (int)diffTop);
                    lastMousePosition = new Point((int)marginLeft, (int)marginTop);
                    updateImage();
                    updateDataSource();
                }catch
                {
                    MessageBox.Show("Number Format Is Wrong");
                }
            }
        }

        private void pic_preview_MouseEnter(object sender, EventArgs e)
        {            
            Cursor.Current = Cursors.Hand;
        }

        private void pic_preview_MouseMove(object sender, MouseEventArgs e)
        {
            Cursor.Current = Cursors.Hand;
            if (e.Button == MouseButtons.Left && dragenabled)
            {
                Point currentPosition = e.Location;
                Console.WriteLine(e.Location);

                int diffX = (currentPosition.X - lastMousePosition.X)*imageList[currentIdx].Width/pic_preview.Width;
                int diffY = (currentPosition.Y - lastMousePosition.Y)*imageList[currentIdx].Height/pic_preview.Height;
                pages[currentIdx].movePixelXY(diffX, diffY);
                foreach (String key in book.PageData[currentIdx].AttributeName)
                {
                    PointF val=book.PageData[currentIdx].GetData(key);
                    val.X += Constants.PixelXToMilimeter(diffX);
                    val.Y += Constants.PixelYToMilimeter(diffY);
                    book.PageData[currentIdx].SetData(key, val);
                }
                lastMousePosition = currentPosition;
                update();
            }
        }

        private void update()
        {
            updateImage();
            updateMMText();
            //updateDataSource();
        }

        private void updateMMText()
        {
            if (currentIdx < pages.Count)
            {
                margin_left.Text = Constants.PixelXToMilimeter(pages[currentIdx].getTopLeftX()) + "";
                margin_top.Text = Constants.PixelYToMilimeter(pages[currentIdx].getTopLeftY()) + "";
            }
        }

        private void pic_preview_Click(object sender, EventArgs e)
        {
        }

        private void pic_preview_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && !isDrag)
            {
                isDrag = true;
                lastMousePosition = e.Location;
            }
        }

        private void pic_preview_MouseUp(object sender, MouseEventArgs e)
        {
            if (isDrag)
            {
                isDrag = false;
            }
            updateDataSource();
        }

        private void Preview_Load(object sender, EventArgs e)
        {

        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                String filename = sfd.FileName;
                //Templates.Save(pages, filename);
                for(int i=0;i<pages.Count;i++)
                {
                    List<int> indices = new List<int>();
                    for (int j = 0; j < book.PageData[i].AttributeName.Count;j++ )
                    {
                        String key = book.PageData[i].AttributeName[j];
                        if (book.PageData[i].IsVisible(key))
                        {
                            indices.Add(j);
                        }
                    }
                    for (int j = 0; j < pages[i].pointArray.Count; j++)
                    {
                        PointF point=pages[i].pointArray[j];
                        point=new PointF(Constants.PixelXToMilimeter(point.X),Constants.PixelYToMilimeter(point.Y));
                        book.PageData[i].SetData(book.PageData[i].AttributeName[indices[j]], point);
                    }
                }
                book.Save(filename);
                collections.UpdateBookPath(filename);
            }
        }

        private void btn_load_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            dragenabled = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                String filename = ofd.FileName;
                BookData book = BookData.Load(filename);
                if (book.Name.Equals(licenseName, StringComparison.OrdinalIgnoreCase))
                {
                    collections.UpdateBookPath(filename);
                    this.book = book;
                    currentIdx = 0;
                    pages.Clear();
                    Users user=new Users(userId,licenseID);
                    foreach (PageData pg in book.PageData)
                    {
                        List<string> dataList=new List<string>();
                        List<PointF> pointarray=new List<PointF>();
                        foreach(String key in pg.AttributeName)
                        {
                            if (pg.IsVisible(key))
                            {
                                dataList.Add(user.getDataFromKey(key));
                                pointarray.Add(pg.GetData(key));
                            }
                        }
                        Page page = new Page(dataList, pointarray);
                        pages.Add(page);
                    }
                    margin_left.Text = "0";
                    margin_top.Text = "0";
                    updateDataSource();
                    update();
                }
                else
                {
                    // error
                    MessageBox.Show("Nama lisensi yang akan dicetak berbeda dengan nama lisensi template yang akan dibuka.", "Error template", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                /*
                List<Point> points=Templates.Load(filename);
                Point point;
                for(int i=0;i<points.Count && i<pages.Count;i++)
                {
                    point = points[i];
                    float marginLeft = point.X;
                    float marginTop = point.Y;
                    float diffLeft = marginLeft - this.pages[i].getTopLeftX();
                    float diffTop = marginTop - this.pages[i].getTopLeftY();
                    ((Page)(this.pages[i])).movePixelXY((int)diffLeft, (int)diffTop);
                    update();
                }
                 */
            }
            dragenabled = true;
        }

        private void updateDataSource()
        {
            this.tbl_datasrc.Rows.Clear();
            List<string> currentData = new List<string>(this.pages[currentIdx].dataList);
            List<PointF> currPos = new List<PointF>(this.pages[currentIdx].pointArray);
            int maxCount = (currentData.Count > currPos.Count ? currentData.Count : currPos.Count);

            if (currentData.Count < maxCount)
            {
                int diff = currentData.Count - maxCount;
                for (int i = 0; i < diff; i++)
                {
                    currentData.Add("");
                }
            }

            if (currPos.Count < maxCount)
            {
                int diff = currPos.Count - maxCount;
                for (int i = 0; i < diff; i++)
                {
                    currPos.Add(new PointF(0, 0));
                }
            }

            for (int i = 0; i < currPos.Count; i++)
            {
                string pos = Constants.PixelXToMilimeter(currPos[i].X) + "x" + Constants.PixelYToMilimeter(currPos[i].Y);
                List<string> data = new List<string> { currentData[i],pos };
                addDataToDataGridView(data);
            }
          
        }

        private void addDataToDataGridView(List<string> data)
        {            
            DataGridViewRow row = new DataGridViewRow();
            //row.Height = 400;
            row.MinimumHeight = 30;
            data.Add("Delete");
            row.CreateCells(tbl_datasrc, data.ToArray());
            tbl_datasrc.Rows.Add(row);
        }

        private void tbl_datasrc_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                int rowsCount = tbl_datasrc.Rows.Count;
                List<string> newData = new List<string>();
                for (int i = 0; i < rowsCount; i++)
                {
                    string s = (string)tbl_datasrc.Rows[i].Cells[0].Value;
                    if (s != null)
                    {
                        newData.Add(s);
                    }
                }
                this.pages[currentIdx].dataList = new List<string>(newData);
                update();
            }
        }

        private void tbl_datasrc_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                string value = (string)tbl_datasrc.Rows[e.RowIndex].Cells[1].Value;
                string[] result = Regex.Split(value, "x");
                float marginLeft = (float)Double.Parse(result[0]);
                float margintop = (float)Double.Parse(result[1]);

                marginWindowEdit mwe = new marginWindowEdit(marginLeft, margintop);
                mwe.ShowDialog();

                if (!mwe.isCanceled && e.RowIndex < this.pages[currentIdx].pointArray.Count)
                {
                    this.pages[currentIdx].pointArray[e.RowIndex] = new PointF(Constants.MilimeterXToPixel(mwe.marginleft), Constants.MilimeterYToPixel(mwe.margintop));
                }
                update();
                updateDataSource();
            }
        }

        private void tbl_datasrc_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void tbl_datasrc_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                string value = (string)tbl_datasrc.Rows[e.RowIndex].Cells[1].Value;
                if (value != null)
                {
                    string[] result = Regex.Split(value, "x");
                    float marginLeft = (float)Double.Parse(result[0]);
                    float margintop = (float)Double.Parse(result[1]);

                    marginWindowEdit mwe = new marginWindowEdit(marginLeft, margintop);
                    mwe.ShowDialog();

                    if (!mwe.isCanceled && e.RowIndex < this.pages[currentIdx].pointArray.Count)
                    {
                        this.pages[currentIdx].pointArray[e.RowIndex] = new PointF(Constants.MilimeterXToPixel(mwe.marginleft),Constants.MilimeterYToPixel( mwe.margintop));
                        update();
                        updateDataSource();
                    }
                    
                }
            }
        }

        private void btn_adddata_Click(object sender, EventArgs e)
        {
            AddDataWindow datawindow = new AddDataWindow();
            datawindow.ShowDialog();

            if (!datawindow.isCanceled)
            {
                this.pages[currentIdx].dataList.Add(datawindow.data);
                this.pages[currentIdx].pointArray.Add(new PointF(datawindow.marginleft, datawindow.margintop));
                update();
                updateDataSource();
            }
        }

        private void tbl_datasrc_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == tbl_datasrc.Columns.Count - 1)
            {
                if (e.RowIndex < this.pages[currentIdx].pointArray.Count)
                {
                    this.pages[currentIdx].dataList.RemoveAt(e.RowIndex);
                    this.pages[currentIdx].pointArray.RemoveAt(e.RowIndex);
                    update();
                    updateDataSource();
                }
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

       
    }
}
